package com.platform.server.service.impl;

import com.alipay.api.internal.util.AlipaySignature;
import com.platform.server.common.Constant;
import com.platform.server.dao.MessageDao;
import com.platform.server.dao.PayOrderDao;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.VipDao;
import com.platform.server.entity.Order;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.PayOrderService;
import com.platform.server.service.ServerService;
import com.platform.server.util.AlipayCons;
import com.platform.server.util.AlipayUtil;
import com.platform.server.util.AuroraPush;
import com.platform.server.util.DateUtils;
import com.platform.server.util.HttpUtil;
import com.platform.server.util.WeixinCons;
import com.platform.server.util.WeixinPayUtil;
import com.platform.server.util.WxpayDemoUtils;
import com.platform.server.util.XMLUtil;
import com.szrca.ima.utils.StringTools;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/5/17 0017.
 */
@Transactional
@Service
public class PayOrderServiceImpl extends BaseService implements PayOrderService {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private PayOrderDao payOrderDao;

	@Autowired
	private ServerDao serverDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private VipDao vipDao;

	@Autowired
	private MessageDao messageDao;

	@Autowired
	private ServerService serverService;

	/**
	 * 支付宝支付调用需要参数
	 *
	 * @param body
	 *            订单描述
	 * @param subject
	 *            订单标题
	 * @param out_trade_no
	 *            商户订单号 orderSn
	 * @param total_amount
	 *            订单总金额，单位为元，精确到小数点后
	 * @param order_id
	 *            回传参数
	 */
	private ReturnData returnAlipayPayParam(String body, String subject, String out_trade_no, String total_amount,
			String order_id) throws Exception {
		String notify_url = AlipayCons.PAY_NOTIFY_URL; // 设置回调地址
		// 公共参数,阿里的一些验证信息..
		Map<String, String> map = new HashMap<String, String>();
		map.put("app_id", AlipayCons.ALIPAY_APP_ID);
		map.put("method", "alipay.trade.app.pay");
		map.put("format", AlipayCons.ALIPAY_FORMAT);
		map.put("charset", AlipayCons.ALIPAY_CHARSET);
		map.put("sign_type", AlipayCons.ALIPAY_SIGN_TYPE);
		map.put("timestamp", DateUtils.getDateFormatter());
		map.put("version", "1.0");
		map.put("notify_url", notify_url);

		// 业务参数,
		Map<String, String> m = new HashMap<String, String>();
		m.put("body", body);
		m.put("subject", subject);
		m.put("out_trade_no", out_trade_no);
		m.put("timeout_express", "30m");
		m.put("total_amount", total_amount);
		m.put("seller_id", AlipayCons.ALIPAY_PARTNER);
		m.put("product_code", "QUICK_MSECURITY_PAY");
		m.put("passback_params", order_id); // 回传参数，回调时原值返回
		// 业务内容:json数据
		JSONObject bizcontentJson = JSONObject.fromObject(m);
		// 将业务内容,放到map中,一起传递过去
		map.put("biz_content", bizcontentJson.toString());
		// 对未签名原始字符串进行签名,,,对参数进行前面
		String rsaSign = AlipaySignature.rsaSign(map, AlipayCons.ALIPAY_PUBLIC_KEY, AlipayCons.ALIPAY_CHARSET);
		logger.info("====================================end AlipayService returnPayParam notify_url" + notify_url);
		// 最后对请求字符串的所有一级value（biz_content作为一个value）进行encode，编码格式按请求串中的charset为准，没传charset按UTF-8处理
		map.put("biz_content", URLEncoder.encode(bizcontentJson.toString(), AlipayCons.ALIPAY_CHARSET));
		// Map par = AlipayUtil.paraFilter(map4); //除去数组中的空值和签名参数
		String json4 = AlipayUtil.createLinkString(map); // 拼接后的字符串
		StringBuffer jsonBuffer = new StringBuffer(json4).append("&sign=")
				.append(URLEncoder.encode(rsaSign, AlipayCons.ALIPAY_CHARSET));
		logger.info("====================================end AlipayService returnPayParam" + jsonBuffer.toString());
		return new ReturnData(jsonBuffer.toString());
	}

	/**
	 * 调用支付返回参数
	 *
	 * @param body
	 *            商品描述
	 * @param out_trade_no
	 *            商户订单号
	 * @param total_fee
	 *            标价金额
	 * @param order_id
	 *            回传参数
	 */
	private ReturnData returnWXPayParam(String body, String out_trade_no, Integer total_fee, String order_id,
			String loca_ip) throws Exception {
		ReturnData returnData = new ReturnData();
		logger.info("returnPayParam ---" + body + ",,,out_trade_no=" + out_trade_no + ",total_fee=" + total_fee
				+ ",,order_id=" + order_id);
		try {
			String nonce_str = getRandomString(32); // strTime + strRandom;
			// 获取发起电脑 ip
			// String loca_ip = request.getRemoteAddr();// 获得本机IP
			JSONObject jso = new JSONObject();
			// 账号信息
			String appid = WeixinCons.WX_APP_ID; // appid
			// String appsecret = WeixinCons.app_secret; // appsecret
			String mch_id = WeixinCons.WX_MACH_ID; // 商业号
			String api_key = WeixinCons.WX_APP_KEY; // key
			String notify_url = "";
			notify_url = WeixinCons.WX_PAY_NOTIFY_URL;
			logger.info("========================notify_url:" + notify_url);
			// 封装参数
			SortedMap<String, String> signParams = new TreeMap<String, String>();
			signParams.put("appid", appid);// app_id
			signParams.put("body", body);// 商品参数信息
			signParams.put("mch_id", mch_id);// 微信商户账号
			signParams.put("nonce_str", nonce_str);// 32位不重复的编号
			signParams.put("notify_url", notify_url);// 回调页面
			signParams.put("out_trade_no", out_trade_no);// 订单编号
			signParams.put("spbill_create_ip", loca_ip);// 请求的实际ip地址
			signParams.put("total_fee", String.valueOf(total_fee));// 支付金额 单位为分
			signParams.put("trade_type", "APP");// 付款类型为APP
			signParams.put("attach", order_id); // 附加数据，回调时原值返回
			String sign = WeixinPayUtil.createSign("UTF-8", signParams);// 生成签名
			signParams.put("sign", sign);
			signParams.remove("key");// 调用统一下单无需key（商户应用密钥）
			String requestXml = WeixinPayUtil.getRequestXml(signParams);// 生成Xml格式的字符串
			logger.info("----------------requestXML:" + requestXml);
			// 调用统一支付接口
			String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);
			System.out.println("////////////////////////\n" + resXml);

			// 返回的result成功结果取出prepay_id：
			Map map = XMLUtil.doXMLParse(resXml);
			String return_code = (String) map.get("return_code");
			String return_msg = (String) map.get("return_msg");
			String prepay_id = null;
			if (return_code.contains("SUCCESS")) {
				prepay_id = (String) map.get("prepay_id");// 获取到prepay_id
			} else {
				returnData.setMsg("请求返回有误");
				returnData.setCode(2);
				returnData.setData(false);
				return returnData;
			}
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			jso.put("appid", appid);// app_id
			jso.put("partnerid", mch_id);// 微信商户账号
			jso.put("prepayid", prepay_id);// 预付订单id
			jso.put("package", "Sign=WXPay");// 默认sign=WXPay
			jso.put("noncestr", nonce_str);// 自定义不重复的长度不长于32位
			jso.put("timestamp", timestamp);// 北京时间时间戳

			SortedMap<String, String> signParam = new TreeMap<String, String>();
			signParam.put("appid", appid);// app_id
			signParam.put("partnerid", mch_id);// 微信商户账号
			signParam.put("prepayid", prepay_id);// 预付订单id
			signParam.put("package", "Sign=WXPay");// 默认sign=WXPay
			signParam.put("noncestr", nonce_str);// 自定义不重复的长度不长于32位
			signParam.put("timestamp", timestamp);// 北京时间时间戳
			String signAgain = WeixinPayUtil.createSign("UTF-8", signParam);// 再次生成签名
			jso.put("sign", signAgain);

			System.out.println(jso);

			returnData = new ReturnData(jso);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnData;
	}

	/**
	 * 表示生成字符串的长度
	 */
	private static String getRandomString(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 微信回调
	 */
	public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("-------------------------------------------begin notify");
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("-------------------------------------------begin notify s:" + sb.toString());
			// 解析xml成map
			Map<String, String> m = new HashMap<String, String>();
			m = XMLUtil.doXMLParse(sb.toString());
			logger.info("-------------------------------------------begin notify param:" + m);
			// 过滤空 设置 TreeMap
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			Iterator it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 账号信息
			String key = WeixinCons.WX_APP_KEY; // key

			logger.info(packageParams.toString());
			// 判断签名是否正确
			if (WeixinPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
				// ------------------------------
				// 处理业务开始
				// ------------------------------
				String resXml = "";
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
					// 这里是支付成功
					////////// 执行自己的业务逻辑////////////////
					String mch_id = (String) packageParams.get("mch_id");
					String openid = (String) packageParams.get("openid");
					String is_subscribe = (String) packageParams.get("is_subscribe");
					String out_trade_no = (String) packageParams.get("out_trade_no");

					String total_fee = (String) packageParams.get("total_fee");

					logger.info("mch_id:" + mch_id);
					logger.info("openid:" + openid);
					logger.info("is_subscribe:" + is_subscribe);
					logger.info("out_trade_no:" + out_trade_no);
					logger.info("total_fee:" + total_fee);
					////////// 执行自己的业务逻辑////////////////
					String attach = (String) packageParams.get("attach");
					String[] split = attach.split(",");
					String userid = split[0];
					String payMethod = split[1];
					String payMoney = split[2];
					String orderid = split[3];
					String type = split[4];
					/**
					 * 增加用户记录
					 */
					Map<String, Object> map1 = serverDao.selectUserMoney(userid);
					String money = map1.get("money").toString();
					Map<String, Object> platform_map = serverDao.selectUserMoney("1");
					String platform_money = platform_map.get("money").toString();
					serverDao.insertCancelOrder(userid, payMoney, "会员", orderid, Double.valueOf(money) + "",
							Constant.EXPEND, Double.valueOf(platform_money) + Double.valueOf(payMoney) + "", null);
					// serverDao.insertCancelOrder("1", payMoney, "平台会员收入",
					// orderid, Double.valueOf(platform_money) +
					// Double.valueOf(payMoney) + "", Constant.INCOME);
					platform_money = Double.valueOf(platform_money) + Double.valueOf(payMoney) + "";
					String selectEnterUser = userDao.selectEnterUser(userid);
					String is_auth = "1";
					if (!StringTools.isEmpty(selectEnterUser) && selectEnterUser.equals("1")) {
						is_auth = "2";
					}
					DecimalFormat df = new DecimalFormat("######0.00");
					Map<String, Object> selectRate2 = serverDao.selectRate();
					Double royalty = 0D;
					if (type.equals("1")) {
						String selectParent = userDao.selectParent(userid);
						if (!StringTools.isEmpty(selectParent)) {
							String selectEntMember1 = serverDao.selectisVip1(selectParent);
							String selectEntMember2 = serverDao.selectisVip2(selectParent);
							Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
							String money1 = map2.get("money").toString();
							if (!StringTools.isEmpty(selectEntMember1) && selectEntMember1.equals("1")) {
								royalty += Double.parseDouble(selectRate2.get("vip_recommend_one").toString());
								serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
										Double.valueOf(money1) + royalty + "", Constant.INCOME,
										Double.valueOf(platform_money) - royalty + "", null, userid);
								// 加入提成
								Map<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("user_id", selectParent);
								hashMap.put("money", royalty);
								serverDao.updateServerUserMoney(hashMap);
							}
							if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
								royalty += Double.parseDouble(selectRate2.get("twovip_recommend_one").toString());
								serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
										Double.valueOf(money1) + royalty + "", Constant.INCOME,
										Double.valueOf(platform_money) - royalty + "", null, userid);
								// 加入提成
								Map<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("user_id", selectParent);
								hashMap.put("money", royalty);
								serverDao.updateServerUserMoney(hashMap);
							}
						}
					}
					if (type.equals("2")) {
						is_auth = "3";
						String selectParent = userDao.selectParent(userid);
						if (!StringTools.isEmpty(selectParent)) {
							String selectEntMember2 = serverDao.selectisVip2(selectParent);
							Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
							String money1 = map2.get("money").toString();
							if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
								royalty += Double.parseDouble(selectRate2.get("twovip_recommend_two").toString());
								serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
										Double.valueOf(money1) + royalty + "", Constant.INCOME,
										Double.valueOf(platform_money) - royalty + "", null, userid);
								// 加入提成
								Map<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("user_id", selectParent);
								hashMap.put("money", royalty);
								serverDao.updateServerUserMoney(hashMap);
							}
						}
					}
					if (type.equals("3")) {
						String selectParent = userDao.selectParent(userid);
						if (!StringTools.isEmpty(selectParent)) {
							String selectEntMember1 = serverDao.selectisVip1(selectParent);
							String selectEntMember2 = serverDao.selectisVip2(selectParent);
							Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
							String money1 = map2.get("money").toString();
							if (!StringTools.isEmpty(selectEntMember1) && selectEntMember1.equals("1")) {
								royalty += Double.parseDouble(selectRate2.get("vip_recommend_ent").toString());
								serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
										Double.valueOf(money1) + royalty + "", Constant.INCOME,
										Double.valueOf(platform_money) - royalty + "", null, userid);
								// 加入提成
								Map<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("user_id", selectParent);
								hashMap.put("money", royalty);
								serverDao.updateServerUserMoney(hashMap);
							}
							if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
								royalty += Double.parseDouble(selectRate2.get("twovip_recommend_ent").toString());
								serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
										Double.valueOf(money1) + royalty + "", Constant.INCOME,
										Double.valueOf(platform_money) - royalty + "", null, userid);
								// 加入提成
								Map<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("user_id", selectParent);
								hashMap.put("money", royalty);
								serverDao.updateServerUserMoney(hashMap);
							}
						}
					}
					serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(royalty) + "");
					// 添加自己的消息
					Map<String, Object> hm = new HashMap<>();
					hm.put("title", "购买会员成功");
					hm.put("type", "1");
					hm.put("recevicer_id", userid);
					hm.put("content", "购买会员成功");
					messageDao.insertMessage(hm);
					// 成为会员之前查看该用户是否有开通过会员
					Map<String, Object> map = vipDao.selectVipCount(userid);
					if (map != null) {
						// 修改该用户的开通会员次数
						Integer counts = Integer.parseInt(map.get("counts").toString()) + 1;
						vipDao.updateVip(userid, payMethod, payMoney, orderid, counts.toString(), is_auth);

					} else {
						vipDao.insertVip(userid, payMethod, payMoney, orderid, is_auth);
					}
					// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

				} else {
					logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				// ------------------------------
				// 处理业务完毕
				// ------------------------------
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
				logger.info("通知签名验证失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 支付宝回调
	 */
	public String aliNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("====================================begin AlipayService notify");
		String returnStr = "";
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				logger.info("====================================================param s:" + s);
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("====================================================param InputStream:" + sb.toString());
			// 接收支付宝返回的请求参数
			Map<String, String> params = AlipayUtil.createLinkMap(sb.toString());

			logger.info("====================================================param params:" + params);
			String trade_status = params.get("trade_status");
			String out_trade_no = params.get("out_trade_no");
			// String notify_id =
			// json.get("notify_id").toString().substring(2,json.get("notify_id").toString().length()-2);

			logger.info("商户的订单编号：" + out_trade_no);
			logger.info("支付的状态：" + trade_status);

			if (trade_status != null && trade_status.equals("TRADE_SUCCESS")) {

				/**
				 * 支付成功之后的业务处理
				 */
				String passback_paramss = params.get("passback_params");
				String passback_params = URLDecoder.decode(passback_paramss, "utf-8");

				String[] split = passback_params.split(",");
				String userid = split[0];
				String payMethod = split[1];
				String payMoney = split[2];
				String orderid = split[3];
				String type = split[4];
				/**
				 * 增加用户记录
				 */
				Map<String, Object> map1 = serverDao.selectUserMoney(userid);
				String money = map1.get("money").toString();
				Map<String, Object> platform_map = serverDao.selectUserMoney("1");
				String platform_money = platform_map.get("money").toString();
				serverDao.insertCancelOrder(userid, payMoney, "会员", orderid, Double.valueOf(money) + "",
						Constant.EXPEND, Double.valueOf(platform_money) + Double.valueOf(payMoney) + "", null);
				// serverDao.insertCancelOrder("1", payMoney, "平台会员收入", orderid,
				// Double.valueOf(platform_money) + Double.valueOf(payMoney) +
				// "", Constant.INCOME);
				platform_money = Double.valueOf(platform_money) + Double.valueOf(payMoney) + "";
				String selectEnterUser = userDao.selectEnterUser(userid);
				String is_auth = "1";
				if (!StringTools.isEmpty(selectEnterUser) && selectEnterUser.equals("1")) {
					is_auth = "2";
				}
				DecimalFormat df = new DecimalFormat("######0.00");
				Map<String, Object> selectRate2 = serverDao.selectRate();
				Double royalty = 0D;
				if (type.equals("1")) {
					String selectParent = userDao.selectParent(userid);
					if (!StringTools.isEmpty(selectParent)) {
						String selectEntMember1 = serverDao.selectisVip1(selectParent);
						String selectEntMember2 = serverDao.selectisVip2(selectParent);
						Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
						String money1 = map2.get("money").toString();
						if (!StringTools.isEmpty(selectEntMember1) && selectEntMember1.equals("1")) {
							royalty += Double.parseDouble(selectRate2.get("vip_recommend_one").toString());
							serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
									Double.valueOf(money1) + royalty + "", Constant.INCOME,
									Double.valueOf(platform_money) - royalty + "", null, userid);
							// 加入提成
							Map<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("user_id", selectParent);
							hashMap.put("money", royalty);
							serverDao.updateServerUserMoney(hashMap);
						}
						if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
							royalty += Double.parseDouble(selectRate2.get("twovip_recommend_one").toString());
							serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
									Double.valueOf(money1) + royalty + "", Constant.INCOME,
									Double.valueOf(platform_money) - royalty + "", null, userid);
							// 加入提成
							Map<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("user_id", selectParent);
							hashMap.put("money", royalty);
							serverDao.updateServerUserMoney(hashMap);
						}
					}
				}
				if (type.equals("2")) {
					is_auth = "3";
					String selectParent = userDao.selectParent(userid);
					if (!StringTools.isEmpty(selectParent)) {
						String selectEntMember2 = serverDao.selectisVip2(selectParent);
						Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
						String money1 = map2.get("money").toString();
						if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
							royalty += Double.parseDouble(selectRate2.get("twovip_recommend_two").toString());
							serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
									Double.valueOf(money1) + royalty + "", Constant.INCOME,
									Double.valueOf(platform_money) - royalty + "", null, userid);
							// 加入提成
							Map<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("user_id", selectParent);
							hashMap.put("money", royalty);
							serverDao.updateServerUserMoney(hashMap);
						}
					}
				}
				if (type.equals("3")) {
					String selectParent = userDao.selectParent(userid);
					if (!StringTools.isEmpty(selectParent)) {
						String selectEntMember1 = serverDao.selectisVip1(selectParent);
						String selectEntMember2 = serverDao.selectisVip2(selectParent);
						Map<String, Object> map2 = serverDao.selectUserMoney(selectParent);
						String money1 = map2.get("money").toString();
						if (!StringTools.isEmpty(selectEntMember1) && selectEntMember1.equals("1")) {
							royalty += Double.parseDouble(selectRate2.get("vip_recommend_ent").toString());
							serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
									Double.valueOf(money1) + royalty + "", Constant.INCOME,
									Double.valueOf(platform_money) - royalty + "", null, userid);
							// 加入提成
							Map<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("user_id", selectParent);
							hashMap.put("money", royalty);
							serverDao.updateServerUserMoney(hashMap);
						}
						if (!StringTools.isEmpty(selectEntMember2) && selectEntMember2.equals("1")) {
							royalty += Double.parseDouble(selectRate2.get("twovip_recommend_ent").toString());
							serverDao.insertRoyaltyOrder(selectParent, royalty + "", "会员提成", orderid,
									Double.valueOf(money1) + royalty + "", Constant.INCOME,
									Double.valueOf(platform_money) - royalty + "", null, userid);
							// 加入提成
							Map<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("user_id", selectParent);
							hashMap.put("money", royalty);
							serverDao.updateServerUserMoney(hashMap);
						}
					}
				}
				serverDao.returnUserMoney("1", Double.valueOf(platform_money) - Double.valueOf(royalty) + "");
				// 添加自己的消息
				Map<String, Object> hm = new HashMap<>();
				hm.put("title", "购买会员成功");
				hm.put("type", "1");
				hm.put("recevicer_id", userid);
				hm.put("content", "购买会员成功");
				messageDao.insertMessage(hm);
				// 成为会员之前查看该用户是否有开通过会员
				Map<String, Object> map = vipDao.selectVipCount(userid);
				if (map != null) {
					// 修改该用户的开通会员次数
					Integer counts = Integer.parseInt(map.get("counts").toString()) + 1;
					vipDao.updateVip(userid, payMethod, payMoney, orderid, counts.toString(), is_auth);

				} else {
					vipDao.insertVip(userid, payMethod, payMoney, orderid, is_auth);
				}
				// param.put("orId", passback_params);
				// param.put("orSn", out_trade_no);
				logger.info("updatePayOrder---------------id===" + passback_params + "------");
				returnStr = "success";
			} else {

				/**
				 * 支付失败后的业务处理
				 */
				returnStr = "ERROR";

			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "初始值";
		}
		logger.info("====================================end AlipayService notify" + returnStr);
		return returnStr;
	}

	/**
	 * 优惠券微信回调
	 */
	@Override
	public void wxNotify2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();
		logger.info("-------------------------------------------begin notify s:" + sb.toString());
		// 解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		m = XMLUtil.doXMLParse(sb.toString());
		logger.info("-------------------------------------------begin notify param:" + m);
		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		// 账号信息
		String key = WeixinCons.WX_APP_KEY; // key

		logger.info(packageParams.toString());
		// 判断签名是否正确
		if (WeixinPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
			// ------------------------------
			// 处理业务开始
			// ------------------------------
			String resXml = "";
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 这里是支付成功
				////////// 执行自己的业务逻辑////////////////
				String mch_id = (String) packageParams.get("mch_id");
				String openid = (String) packageParams.get("openid");
				String is_subscribe = (String) packageParams.get("is_subscribe");
				String out_trade_no = (String) packageParams.get("out_trade_no");

				String total_fee = (String) packageParams.get("total_fee");

				logger.info("mch_id:" + mch_id);
				logger.info("openid:" + openid);
				logger.info("is_subscribe:" + is_subscribe);
				logger.info("out_trade_no:" + out_trade_no);
				logger.info("total_fee:" + total_fee);
				////////// 执行自己的业务逻辑////////////////
				String attach = (String) packageParams.get("attach");
				// param.put("orId", passback_params);
				// param.put("orSn", out_trade_no);
				String[] split = attach.split(",");
				// 类型1活动优惠券 2普通优惠券
				String type = split[0];
				// 活动优惠券或者普通优惠券id
				String discountid = split[1];
				// 用户id
				String userid = split[2];
				// 充值金额
				String moneys = split[3];
				Double mon = Double.parseDouble(moneys) / 100D;
				// 增加该用户的余额
				Map<String, Object> userMap = new HashMap<>();
				userMap.put("user_id", userid);
				userMap.put("money", mon);
				payOrderDao.insertUserwallet(userMap);
				Double money = Double.valueOf(serverDao.selectUserMoney(userid).get("money").toString());
				Map<String, Object> platform_map = serverDao.selectUserMoney("1");
				String platform_money = platform_map.get("money").toString();
				serverDao.insertCancelOrder(userid, mon + "", "充值余额", out_trade_no, money + "", Constant.INCOME,
						Double.valueOf(platform_money) + "", null);
				//serverDao.returnUserMoney("1", Double.valueOf(platform_money) + Double.valueOf(mon) + "");
				List<Map<String,Object>> selectUserArrearage = serverDao.selectUserArrearage();
		    	for (Map<String, Object> map : selectUserArrearage) {
		    		if(map.get("defaulter_id").toString().equals(userid)){
		    			 Map<String, Object> m3 = serverDao.selectUserMoney(userid);
		    			  Double m2= (Double) m3.get("money");
		    			  if(m2>=30D){
		    				  Map<String, Object> map1 = serverDao.selectUserMoney(map.get("user_id").toString());
		    				  Double money3 = (Double) map1.get("money");
		    				  String s1 = userDao.selectUserMoney("1");
		    				  serverDao.returnUserMoney(map.get("user_id").toString(), money3+30+"");
		    				  serverDao.insertCancelOrder(map.get("user_id").toString(), "30", "服务方违约金收入", map.get("order_id").toString(),money3+30 + "", Constant.INCOME, s1, null);
		    				  Double money4 = money - 30;
		    				  serverDao.returnUserMoney(userid, money4.toString());
		    				  serverDao.insertCancelOrder(userid, "30", "服务违约支出", map.get("order_id").toString(), money4 + "", Constant.INCOME, s1, null);
		    				  serverDao.deleteArrearage(map.get("id").toString());	
		    			  }
		    		}
				}
				// serverDao.insertCancelOrder("1", mon + "", "充值余额",
				// out_trade_no, money + "",
				// Constant.INCOME,Double.valueOf(platform_money)+Double.valueOf(mon)+"",null);
				// 添加自己的消息
				Map<String, Object> hm = new HashMap<>();
				hm.put("title", "充值成功");
				hm.put("type", "1");
				hm.put("recevicer_id", userid);
				hm.put("content", "充值成功");
				messageDao.insertMessage(hm);
				// 添加充值记录
				payOrderDao.insertRechargeRecord(userid, mon.toString(), "微信", out_trade_no);
				// 查看充值面额
				Map<String, Object> hashMap = payOrderDao.selectDenomination();
				String str1 = hashMap.get("five_ticket").toString(); // 五元优惠券满多少可用
				String str2 = hashMap.get("ten_ticket").toString(); // 十元优惠券满多少可用
				String str3 = hashMap.get("twenty_ticket").toString(); // 二十元优惠券满多少可用
				String str4 = hashMap.get("fifty_ticket").toString(); // 五十元优惠券满多少可用
				String str5 = hashMap.get("hundred_ticket").toString(); // 一百元优惠券满多少可用
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Calendar c = Calendar.getInstance();
				if ("1".equals(type)) {
					// 查询活动优惠券信息
					Map<String, Object> map = payOrderDao.selectActivityDiscount(discountid);
					// 获取当前时间的后面第几个月时间
					c.add(Calendar.MONTH, Integer.parseInt(map.get("service_life").toString()));
					Integer num1 = Integer.parseInt(map.get("five_ticket").toString()); // 五元优惠券张数
					for (int i = 0; i < num1; i++) {
						payOrderDao.insertUserDiscount("5", str1, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num2 = Integer.parseInt(map.get("ten_ticket").toString()); // 十元优惠券张数
					for (int i = 0; i < num2; i++) {
						payOrderDao.insertUserDiscount("10", str2, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num3 = Integer.parseInt(map.get("twenty_ticket").toString()); // 二十元优惠券张数
					for (int i = 0; i < num3; i++) {
						payOrderDao.insertUserDiscount("20", str3, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num4 = Integer.parseInt(map.get("fifty_ticket").toString()); // 五十元优惠券张数
					for (int i = 0; i < num4; i++) {
						payOrderDao.insertUserDiscount("50", str4, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num5 = Integer.parseInt(map.get("hundred_ticket").toString()); // 一百元优惠券张数
					for (int i = 0; i < num5; i++) {
						payOrderDao.insertUserDiscount("100", str5, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
				} else if ("2".equals(type)) {
					// 查询普通优惠券信息
					Map<String, Object> map = payOrderDao.selectCommonDiscount(discountid);
					// if(map == null){
					// resXml = "<xml>" +
					// "<return_code><![CDATA[FAIL]]></return_code>"
					// + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml>
					// ";
					// }else{
					// 获取当前时间的后面第几个月时间
					c.add(Calendar.MONTH, Integer.parseInt(map.get("service_life").toString()));
					Integer num1 = Integer.parseInt(map.get("five_ticket").toString()); // 五元优惠券张数
					for (int i = 0; i < num1; i++) {
						payOrderDao.insertUserDiscount("5", str1, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num2 = Integer.parseInt(map.get("ten_ticket").toString()); // 十元优惠券张数
					for (int i = 0; i < num2; i++) {
						payOrderDao.insertUserDiscount("10", str2, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num3 = Integer.parseInt(map.get("twenty_ticket").toString()); // 二十元优惠券张数
					for (int i = 0; i < num3; i++) {
						payOrderDao.insertUserDiscount("20", str3, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num4 = Integer.parseInt(map.get("fifty_ticket").toString()); // 五十元优惠券张数
					for (int i = 0; i < num4; i++) {
						payOrderDao.insertUserDiscount("50", str4, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num5 = Integer.parseInt(map.get("hundred_ticket").toString()); // 一百元优惠券张数
					for (int i = 0; i < num5; i++) {
						payOrderDao.insertUserDiscount("100", str5, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					// }
				}
				// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
			} else {
				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}
			// ------------------------------
			// 处理业务完毕
			// ------------------------------
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			// response.getWriter().write(resXml);
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} else {
			logger.info("通知签名验证失败");
		}
	}

	/**
	 * 优惠券支付宝回调
	 */
	@Override
	public String aliNotify2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("====================================begin AlipayService notify");
		String returnStr = "";
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				logger.info("====================================================param s:" + s);
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("====================================================param InputStream:" + sb.toString());
			// 接收支付宝返回的请求参数
			Map<String, String> params = AlipayUtil.createLinkMap(sb.toString());

			logger.info("====================================================param params:" + params);
			String trade_status = params.get("trade_status");
			String out_trade_no = params.get("out_trade_no");
			// String notify_id =
			// json.get("notify_id").toString().substring(2,json.get("notify_id").toString().length()-2);

			logger.info("商户的订单编号：" + out_trade_no);
			logger.info("支付的状态：" + trade_status);

			if (trade_status != null && trade_status.equals("TRADE_SUCCESS")) {
				/**
				 * 支付成功之后的业务处理
				 */
				String passback_paramss = params.get("passback_params");
				String passback_params = URLDecoder.decode(passback_paramss, "utf-8");
				System.out.println(passback_params);
				// param.put("orId", passback_params);
				// param.put("orSn", out_trade_no);
				String[] split = passback_params.split(",");
				// 类型1活动优惠券 2普通优惠券
				String type = split[0];
				// 活动优惠券或者普通优惠券id
				String discountid = split[1];
				// 用户id
				String userid = split[2];
				// 充值金额
				String moneys = split[3];
				// 增加该用户的余额
				Map<String, Object> userMap = new HashMap<>();
				userMap.put("user_id", userid);
				userMap.put("money", Double.parseDouble(moneys));
				payOrderDao.insertUserwallet(userMap);
				Double money = Double.valueOf(serverDao.selectUserMoney(userid).get("money").toString());
				if(money>30D){
					List<Map<String,Object>> selectUserArrearage = serverDao.selectUserArrearage();
			    	for (Map<String, Object> map : selectUserArrearage) {
			    		if(map.get("defaulter_id").toString().equals(userid)){
			    			 Map<String, Object> m = serverDao.selectUserMoney(userid);
			    			  Double m2= (Double) m.get("money");
			    			  if(m2>=30D){
			    				  Map<String, Object> map1 = serverDao.selectUserMoney(map.get("user_id").toString());
			    				  Double money3 = (Double) map1.get("money");
			    				  String s1 = userDao.selectUserMoney("1");
			    				  serverDao.returnUserMoney(map.get("user_id").toString(), money3+30+"");
			    				  serverDao.insertCancelOrder(map.get("user_id").toString(), "30", "服务方违约金收入", map.get("order_id").toString(),money3+30 + "", Constant.INCOME, s1, null);
			    				  Double money4 = money - 30;
			    				  serverDao.returnUserMoney(userid, money4.toString());
			    				  serverDao.insertCancelOrder(userid, "30", "服务违约支出", map.get("order_id").toString(), money4 + "", Constant.INCOME, s1, null);
			    				  serverDao.deleteArrearage(map.get("id").toString());	
			    			  }
			    		}
					}
				}
				Map<String, Object> platform_map = serverDao.selectUserMoney("1");
				String platform_money = platform_map.get("money").toString();
				serverDao.insertCancelOrder(userid, moneys + "", "充值余额", out_trade_no, money + "", Constant.INCOME,
						Double.valueOf(platform_money)  + "", null);
				//serverDao.returnUserMoney("1", Double.valueOf(platform_money) + Double.valueOf(moneys) + "");
				// 添加自己的消息
				Map<String, Object> hm = new HashMap<>();
				hm.put("title", "充值成功");
				hm.put("type", "1");
				hm.put("recevicer_id", userid);
				hm.put("content", "充值成功");
				messageDao.insertMessage(hm);
				// 添加充值记录
				payOrderDao.insertRechargeRecord(userid, moneys, "支付宝", out_trade_no);
				// 查看充值面额
				Map<String, Object> hashMap = payOrderDao.selectDenomination();
				String str1 = hashMap.get("five_ticket").toString(); // 五元优惠券满多少可用
				String str2 = hashMap.get("ten_ticket").toString(); // 十元优惠券满多少可用
				String str3 = hashMap.get("twenty_ticket").toString(); // 二十元优惠券满多少可用
				String str4 = hashMap.get("fifty_ticket").toString(); // 五十元优惠券满多少可用
				String str5 = hashMap.get("hundred_ticket").toString(); // 一百元优惠券满多少可用
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Calendar c = Calendar.getInstance();
				if ("1".equals(type)) {
					// 查询活动优惠券信息
					Map<String, Object> map = payOrderDao.selectActivityDiscount(discountid);
					if (map == null) {
						return "failure";
					}
					// 获取当前时间的后面第几个月时间
					c.add(Calendar.MONTH, Integer.parseInt(map.get("service_life").toString()));
					Integer num1 = Integer.parseInt(map.get("five_ticket").toString()); // 五元优惠券张数
					for (int i = 0; i < num1; i++) {
						payOrderDao.insertUserDiscount("5", str1, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num2 = Integer.parseInt(map.get("ten_ticket").toString()); // 十元优惠券张数
					for (int i = 0; i < num2; i++) {
						payOrderDao.insertUserDiscount("10", str2, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num3 = Integer.parseInt(map.get("twenty_ticket").toString()); // 二十元优惠券张数
					for (int i = 0; i < num3; i++) {
						payOrderDao.insertUserDiscount("20", str3, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num4 = Integer.parseInt(map.get("fifty_ticket").toString()); // 五十元优惠券张数
					for (int i = 0; i < num4; i++) {
						payOrderDao.insertUserDiscount("50", str4, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num5 = Integer.parseInt(map.get("hundred_ticket").toString()); // 一百元优惠券张数
					for (int i = 0; i < num5; i++) {
						payOrderDao.insertUserDiscount("100", str5, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
				} else if ("2".equals(type)) {
					// 查询活动优惠券信息
					Map<String, Object> map = payOrderDao.selectCommonDiscount(discountid);
					if (map == null) {
						return "failure";
					}
					// 获取当前时间的后面第几个月时间
					c.add(Calendar.MONTH, Integer.parseInt(map.get("service_life").toString()));
					Integer num1 = Integer.parseInt(map.get("five_ticket").toString()); // 五元优惠券张数
					for (int i = 0; i < num1; i++) {
						payOrderDao.insertUserDiscount("5", str1, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num2 = Integer.parseInt(map.get("ten_ticket").toString()); // 十元优惠券张数
					for (int i = 0; i < num2; i++) {
						payOrderDao.insertUserDiscount("10", str2, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num3 = Integer.parseInt(map.get("twenty_ticket").toString()); // 二十元优惠券张数
					for (int i = 0; i < num3; i++) {
						payOrderDao.insertUserDiscount("20", str3, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num4 = Integer.parseInt(map.get("fifty_ticket").toString()); // 五十元优惠券张数
					for (int i = 0; i < num4; i++) {
						payOrderDao.insertUserDiscount("50", str4, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
					Integer num5 = Integer.parseInt(map.get("hundred_ticket").toString()); // 一百元优惠券张数
					for (int i = 0; i < num5; i++) {
						payOrderDao.insertUserDiscount("100", str5, map.get("time").toString(), sdf.format(c.getTime()),
								userid);
					}
				}
				 System.out.println("PayOrderServiceImpl.aliNotify2():"+"支付成功了");
				returnStr = "success";
			} else {

				/**
				 * 支付失败后的业务处理
				 */
				returnStr = "failure";

			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "failure";
		}
      System.out.println("PayOrderServiceImpl.aliNotify2():"+returnStr);
		logger.info("====================================end AlipayService notify" + returnStr);
		return returnStr;
	}

	/**
	 * 违约金微信回调
	 */
	@Override
	public void wxNotify3(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("-------------------------------------------begin notify");
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("-------------------------------------------begin notify s:" + sb.toString());
			// 解析xml成map
			Map<String, String> m = new HashMap<String, String>();
			m = XMLUtil.doXMLParse(sb.toString());
			logger.info("-------------------------------------------begin notify param:" + m);
			// 过滤空 设置 TreeMap
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			Iterator it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 账号信息
			String key = WeixinCons.WX_APP_KEY; // key

			logger.info(packageParams.toString());
			// 判断签名是否正确
			if (WeixinPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
				// ------------------------------
				// 处理业务开始
				// ------------------------------
				String resXml = "";
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
					// 这里是支付成功
					////////// 执行自己的业务逻辑////////////////
					String mch_id = (String) packageParams.get("mch_id");
					String openid = (String) packageParams.get("openid");
					String is_subscribe = (String) packageParams.get("is_subscribe");
					String out_trade_no = (String) packageParams.get("out_trade_no");
					String total_fee = (String) packageParams.get("total_fee");
					logger.info("mch_id:" + mch_id);
					logger.info("openid:" + openid);
					logger.info("is_subscribe:" + is_subscribe);
					logger.info("out_trade_no:" + out_trade_no);
					logger.info("total_fee:" + total_fee);
					////////// 执行自己的业务逻辑////////////////
					String attach = (String) packageParams.get("attach");
					String[] split = attach.split(",");
					String userid = split[0]; // 需要支付违约金的用户id
					String gainUserid = split[1]; // 得到违约金的用户id
					String oid = split[2]; // 订单主键id
					String type = split[3];
					String payMoney = split[4];
					if ("1".equals(type)) {
						// 修改订单状态为服务中
						serverDao.updateOrderStatuIsServer(Integer.parseInt(oid));
					} else {
						// 修改订单状态为已取消
						serverDao.updateOrderStatu(Integer.parseInt(oid));
					}
					quXiaoOrder(userid, oid, payMoney);
					// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

				} else {
					logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				// ------------------------------
				// 处理业务完毕
				// ------------------------------
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
				logger.info("通知签名验证失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void quXiaoOrder(String userid, String oid, String payMoney) {
		Order order = serverDao.selectOrderInfo(Integer.valueOf(oid));
		if (order.getOrder_type().equals("2")) {
			quxiaoOrder(userid, payMoney, order);
		} else if (order.getOrder_type().equals("1")) {
			quxiaoOrder(userid, payMoney, order);
		}
		/*if (!com.platform.server.util.StringTools.isEmpty(order.getDiscountid())) {
			// 修改优惠券状态
			serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
		}
		String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
		if (!order.getReality_price().equals("0.00")) {
			selectUserIntegral = String
					.valueOf(Integer.parseInt(selectUserIntegral) - Integer.parseInt(order.getReality_price()));
			serverDao.returnUserIntegral(order.getUser_id(), selectUserIntegral);
			serverDao.insertIntegralRecord(order.getUser_id(),
					order.getReality_price().substring(0, order.getReality_price().indexOf(".")), "积分扣减", null);
		}
		if (!com.platform.server.util.StringTools.isEmpty(order.getIntegral())) {
			// 退还用户积分
			serverDao.returnUserIntegral(order.getUser_id(), selectUserIntegral);
			serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
		}*/
		serverService.insertMsg(userid, order);
	}

	private void quxiaoOrder(String userid, String payMoney, Order order) {
		if (order.getUser_id().equals(userid)) {
			// 平台余额
			Map<String, Object> map2 = serverDao.selectUserMoney("1");
			Double platform_money = Double.valueOf(map2.get("money").toString());
			Map<String, Object> map1 = serverDao.selectUserMoney(order.getUser_id());
			Double user_money = Double.valueOf(map1.get("money").toString());
			   Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
		        if(selectCancelOrder==null&&order.getStatus().equals("已取消")){
		            serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(),
		            		user_money + Double.valueOf(order.getReality_price()) + "", Constant.INCOME,
		            		platform_money - Double.valueOf(order.getReality_price()) + "", null);
		            serverDao.returnUserMoney("1", platform_money - Double.valueOf(order.getReality_price()) + "");
		            serverDao.returnUserMoney(order.getUser_id(), user_money + Double.valueOf(order.getReality_price()) + "");
		       
		            if (!StringTools.isEmpty(order.getDiscountid())) {
			            //修改优惠券状态
			            serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
			        }
		            String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
		            if(Double.valueOf( order.getReality_price())>0){
		            	selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
		            	serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
		            	serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
		            }
			        if (!StringTools.isEmpty(order.getIntegral())) {
			            //退还用户积分
			            serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
			            //最后添加该用户的积分记录
			            serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
			        }
		        
		        
		        
		        
		        }

			user_money=user_money + Double.valueOf(order.getReality_price());
			if(user_money>=30d){
				   Map<String, Object> selectCancelOrder2 = serverDao.selectCancelOrderType(order.getOrder_id(),"需方违约支出");
				   	if(selectCancelOrder2==null){
					map2 = serverDao.selectUserMoney("1");
						 platform_money = Double.valueOf(map2.get("money").toString());
				   		// 1 服务方获取违约金
				   		Map<String, Object> map = serverDao.selectUserMoney(order.getServer_user_id());
				   		Double server_money = Double.valueOf(map.get("money").toString());
				   		serverDao.insertCancelOrder(order.getServer_user_id(), payMoney, "需方违约收入", order.getOrder_id(),
				   				server_money + Double.valueOf(payMoney) + "", Constant.INCOME, platform_money  + "", null);
				   		serverDao.returnUserMoney(order.getServer_user_id(), server_money + Double.valueOf(payMoney) + "");
				   		// 2 需求方支付违约金
				   		map1 = serverDao.selectUserMoney(order.getUser_id());
				   		user_money = Double.valueOf(map1.get("money").toString());
				   		serverDao.insertCancelOrder(order.getUser_id(), payMoney, "需方违约支出", order.getOrder_id(), user_money + "",
				   				Constant.EXPEND, platform_money  + "", null);
				   		//serverDao.returnUserMoney(order.getUser_id(),  user_money - Double.valueOf(payMoney) + "");
				   	}
			}else{
				 serverDao.insertViolate(30.00, order.getUser_id(), order.getOrder_id(),order.getServer_user_id() );
			}
			
			// 4 扣除平台订单金额
			// serverDao.insertCancelOrder("1", order.getReality_price(),
			// "平台预付返还", order.getOrder_id(), platform_money -
			// Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
		}
		if (order.getServer_user_id().equals(userid)) {
			Map<String, Object> map2 = serverDao.selectUserMoney("1");
			Double platform_money = Double.valueOf(map2.get("money").toString());
			// 3 退回订单金额
			Map<String, Object> map3 = serverDao.selectUserMoney(order.getUser_id());
			Double user_money1 = Double.valueOf(map3.get("money").toString());
			   Map<String, Object> selectCancelOrder = serverDao.selectCancelOrder(order.getOrder_id());
		        if(selectCancelOrder==null&&order.getStatus().equals("已取消")){
		        	serverDao.insertCancelOrder(order.getUser_id(), order.getReality_price(), "预付返还", order.getOrder_id(),
							user_money1 + Double.valueOf(order.getReality_price()) + "", Constant.INCOME,
							platform_money - Double.valueOf(order.getReality_price()) + "", null);
					serverDao.returnUserMoney(order.getUser_id(), user_money1 + Double.valueOf(order.getReality_price()) + "");
		            serverDao.returnUserMoney("1", platform_money - Double.valueOf(order.getReality_price()) + "");
 
		            if (!StringTools.isEmpty(order.getDiscountid())) {
			            //修改优惠券状态
			            serverDao.updateDiscountStatus(Integer.parseInt(order.getDiscountid()));
			        }
		            String selectUserIntegral = serverDao.selectUserIntegral(order.getUser_id());
		            if(Double.valueOf( order.getReality_price())>0){
		            	selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(order.getReality_price().substring(0,order.getReality_price().indexOf("."))));
		            	serverDao.returnUserIntegral(order.getUser_id(),selectUserIntegral);
		            	serverDao.insertIntegralRecord(order.getUser_id(),order.getReality_price().substring(0,order.getReality_price().indexOf(".")), "积分扣减", null);
		            }
			        if (!StringTools.isEmpty(order.getIntegral())) {
			            //退还用户积分
			            serverDao.returnUserIntegral(order.getUser_id(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(order.getIntegral())));
			            //最后添加该用户的积分记录
			            serverDao.insertIntegralRecord(order.getUser_id(), order.getIntegral(), "积分返还", null);
			        }
		        
		        }
			
			Map<String, Object> map1 = serverDao.selectUserMoney(order.getServer_user_id());
			Double server_money = Double.valueOf(map1.get("money").toString())+Double.valueOf(payMoney);
			if(server_money>=30d){
				   Map<String, Object> selectCancelOrder2 = serverDao.selectCancelOrderType(order.getOrder_id(),"服务方违约金支出");
				if(selectCancelOrder2==null){
					map2 = serverDao.selectUserMoney("1");
					 platform_money = Double.valueOf(map2.get("money").toString());
					serverDao.insertCancelOrder(order.getServer_user_id(), payMoney, "服务方违约金支出", order.getOrder_id(),
							server_money + "", Constant.EXPEND, platform_money + "", null);
					//serverDao.returnUserMoney(order.getServer_user_id(), server_money- Double.valueOf(payMoney)+ "");
					Map<String, Object> map = serverDao.selectUserMoney(order.getUser_id());
					Double user_money = Double.valueOf(map.get("money").toString());
					serverDao.insertCancelOrder(order.getUser_id(), payMoney, "服务方违约金收入", order.getOrder_id(),
							user_money + Double.valueOf(payMoney) + "", Constant.INCOME, platform_money  + "", null);
					serverDao.returnUserMoney(order.getUser_id(), user_money + Double.valueOf(payMoney) + "");
				}
			}else{
				serverDao.insertViolate(30.00,order.getServer_user_id(), order.getOrder_id(),  order.getUser_id());
			}
			
			
			// 4 扣除平台订单金额
			// serverDao.insertCancelOrder("1", order.getReality_price(),
			// "平台预付返还", order.getOrder_id(), platform_money -
			// Double.valueOf(order.getReality_price()) + "", Constant.EXPEND);
		}
	}

	/**
	 * 违约金支付宝回调
	 */
	@Override
	public String aliNotify3(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("====================================begin AlipayService notify");
		String returnStr = "";
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				logger.info("====================================================param s:" + s);
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("====================================================param InputStream:" + sb.toString());
			// 接收支付宝返回的请求参数
			Map<String, String> params = AlipayUtil.createLinkMap(sb.toString());

			logger.info("====================================================param params:" + params);
			String trade_status = params.get("trade_status");
			String out_trade_no = params.get("out_trade_no");
			// String notify_id =
			// json.get("notify_id").toString().substring(2,json.get("notify_id").toString().length()-2);

			logger.info("商户的订单编号：" + out_trade_no);
			logger.info("支付的状态：" + trade_status);

			System.out.println("支付宝;" + sb.toString());

			if (trade_status != null && trade_status.equals("TRADE_SUCCESS")) {
				System.out.println("进来了;" + sb.toString());
				/**
				 * 支付成功之后的业务处理
				 */
				String passback_paramss = params.get("passback_params");
				String passback_params = URLDecoder.decode(passback_paramss, "utf-8");
				System.out.println("passback_params:" + passback_params);
				String[] split = passback_params.split(",");
				String userid = split[0]; // 需要支付违约金的用户id
				String gainUserid = split[1]; // 得到违约金的用户id
				String oid = split[2]; // 订单主键id
				String type = split[3];
				String payMoney = split[4];
				if ("1".equals(type)) {
					// 修改订单状态为服务中
					serverDao.updateOrderStatuIsServer(Integer.parseInt(oid));
				} else {
					// 修改订单状态为已取消
					serverDao.updateOrderStatu(Integer.parseInt(oid));

				}
				quXiaoOrder(userid, oid, payMoney);
				returnStr = "success";
			} else {
				/**
				 * 支付失败后的业务处理
				 */
				returnStr = "failure";
				System.out.println("失败了;" + sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "failure";
		}
		logger.info("====================================end AlipayService notify" + returnStr);
		return returnStr;
	}

	/**
	 * 支付服务微信回调
	 */
	@Override
	public void wxNotify4(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("-------------------------------------------begin notify");
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("-------------------------------------------begin notify s:" + sb.toString());
			// 解析xml成map
			Map<String, String> m = new HashMap<String, String>();
			m = XMLUtil.doXMLParse(sb.toString());
			logger.info("-------------------------------------------begin notify param:" + m);
			// 过滤空 设置 TreeMap
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			Iterator it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 账号信息
			String key = WeixinCons.WX_APP_KEY; // key

			logger.info(packageParams.toString());
			// 判断签名是否正确
			if (WeixinPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
				// ------------------------------
				// 处理业务开始
				// ------------------------------
				String resXml = "";
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
					// 这里是支付成功
					////////// 执行自己的业务逻辑////////////////
					String mch_id = (String) packageParams.get("mch_id");
					String openid = (String) packageParams.get("openid");
					String is_subscribe = (String) packageParams.get("is_subscribe");
					String out_trade_no = (String) packageParams.get("out_trade_no");

					String total_fee = (String) packageParams.get("total_fee");

					logger.info("mch_id:" + mch_id);
					logger.info("openid:" + openid);
					logger.info("is_subscribe:" + is_subscribe);
					logger.info("out_trade_no:" + out_trade_no);
					logger.info("total_fee:" + total_fee);
					////////// 执行自己的业务逻辑////////////////
					String attach = (String) packageParams.get("attach");
					String[] split = attach.split(",");
					String orderid = split[0]; // 订单id
					String userid = split[1]; // 用户id
					Integer payMoney = (int) Double.parseDouble(split[2]); // 支付金额
					Integer discountid = Integer.parseInt(split[3]); // 优惠券id
					String order_type = split[4]; // 订单类型
					/**
					 * 增加用户取消订单记录
					 */
					// 查看订单详情
					Order order = payOrderDao.selectOrderInfo(orderid, order_type);

					Map<String, Object> map1 = serverDao.selectUserMoney(userid);
					Double user_money = Double.valueOf(map1.get("money").toString());
					Map<String, Object> platform_map2 = serverDao.selectUserMoney("1");
					Double platform_money = Double.valueOf(platform_map2.get("money").toString());
					serverDao.insertCancelOrder(userid, split[2], "预约预付", order.getOrder_id(), user_money + "",
							Constant.EXPEND, platform_money + Double.valueOf(split[2]) + "", null);
					serverDao.returnUserMoney("1", platform_money + Double.valueOf(split[2]) + "");
					// serverDao.insertCancelOrder("1", split[2], "平台订单收入",
					// order.getOrder_id(), platform_money +
					// Double.valueOf(split[2]) + "", Constant.INCOME);

					if (discountid != 0) {
						// 修改优惠券为已使用
						payOrderDao.updateDiscountStatus(discountid);
					}
					// 修改订单状态为已支付
					int flag = payOrderDao.updateOrderStatus(orderid);
					payOrderDao.updatePayType(orderid, "微信");
					// 查看积分使用方式
					Map<String, Object> hashMap = userDao.selectIntegeralWay();
					Integer common_vip = Integer.parseInt(hashMap.get("common_vip").toString()); // 普通会员支付一元获得的积分
					Integer copper_vip = Integer.parseInt(hashMap.get("copper_vip").toString()); // 铜牌会员支付一元获得的积分
					Integer silver_vip = Integer.parseInt(hashMap.get("silver_vip").toString()); // 银牌会员支付一元获得的积分
					Integer gold_vip = Integer.parseInt(hashMap.get("gold_vip").toString()); // 金牌会员支付一元获得的积分
					// 用户支付1元，推荐用户获得的积分
					Integer recommend_integral = Integer.parseInt(hashMap.get("recommend_integral").toString());

					// 查看我的积分
					Map<String, Object> map3 = userDao.selectMyIntegral(userid);
					Integer integral3 = Integer.parseInt(map3.get("integral").toString());
					if (order != null) {
						if (!StringTools.isEmpty(order.getIntegral())) {
							if (Double.valueOf(order.getIntegral()) > 0) {
								// 扣除积分
								payOrderDao.updateUserIntegral(userid,
										integral3 - Double.valueOf(order.getIntegral()) + "");
								// 添加该用户的积分记录
								serverDao.insertIntegralRecord(userid, order.getIntegral(), "积分抵现", null);
							}
						}
					}

					// 查看我的积分
					Map<String, Object> map = userDao.selectMyIntegral(userid);
					Double endintegral = 0.0;// 用户最终的积分
					Double getintegral = 0.0;// 用户奖励的积分
					Integer integral = Integer.parseInt(map.get("integral").toString());
					if (integral > 100000) {
						System.out.println("金牌会员");
						getintegral = Double.valueOf(payMoney) * gold_vip;
						endintegral = Double.valueOf(payMoney) * gold_vip + integral;
					} else if (integral > 10000) {
						System.out.println("银牌会员");
						getintegral = Double.valueOf(payMoney) * silver_vip;
						endintegral = Double.valueOf(payMoney) * silver_vip + integral;
					} else if (integral > 1000) {
						System.out.println("铜牌会员");
						getintegral = Double.valueOf(payMoney) * copper_vip;
						endintegral = Double.valueOf(payMoney) * copper_vip + integral;
					} else {
						System.out.println("普通会员");
						getintegral = Double.valueOf(payMoney) * common_vip;
						endintegral = Double.valueOf(payMoney) * common_vip + integral;
					}
					// 修改用户积分
					int flag2 = payOrderDao.updateUserIntegral(userid, endintegral.toString());

					// 添加该用户的积分记录
					int f = serverDao.insertIntegralRecord(userid, getintegral.toString(), "支付奖励", null);
					// 接着查看用户的推荐用户信息
//					List<Map<String, Object>> recommendid = payOrderDao.selectRecommendUserInfo(userid);
//					if (recommendid.size() > 0 && recommendid != null) {
//						for (Map<String, Object> mapre : recommendid) {
//							Integer recommend = Integer.valueOf((int) (Double.valueOf(payMoney) * recommend_integral)); // 推荐用户的奖励积分
//							// 查看推荐用户的积分
//							Map<String, Object> map2 = userDao.selectMyIntegral(mapre.get("id").toString());
//							Integer integral2 = Integer.parseInt(map2.get("integral").toString());
//							Integer endintegral2 = Integer.valueOf((int) (Double.valueOf(payMoney) * recommend_integral))
//									+ integral2;
//							// 修改推荐用户积分
//							int flag3 = payOrderDao.updateUserIntegral(mapre.get("id").toString(),
//									endintegral2.toString());
//							// 添加推荐用户的积分记录
//							int fg = serverDao.insertIntegralRecord(mapre.get("id").toString(), recommend.toString(),
//									"积分奖励", userid);
//						}
//					}
					// 添加自己的消息
					Map<String, Object> hm = new HashMap<>();
					hm.put("title", "您已预约了一条服务，请注意查看");
					hm.put("type", "1");
					hm.put("recevicer_id", userid);
					hm.put("content", "您已预约了一条服务，请注意查看");
					messageDao.insertMessage(hm);

					// 添加自己的消息
					Map<String, Object> hm2 = new HashMap<>();
					hm2.put("title", "您的服务已被预约，请注意查看");
					hm2.put("type", "1");
					hm2.put("recevicer_id", order.getServer_user_id());
					hm2.put("content", "您的服务已被预约，请注意查看");
					messageDao.insertMessage(hm2);
					if ("2".equals(order_type)) {
						// 修改该需求单号为已完成
						serverDao.demandSure(Integer.parseInt(order.getServer_id()));
						serverDao.updateOrder(order.getServer_id(), "2");
						List<Map<String, Object>> lists = serverDao
								.selectApplyUserInfo(Integer.parseInt(order.getServer_id()));
						for (int i = 0; i < lists.size(); i++) {
							if (lists.get(i).get("id").toString().equals(order.getServer_user_id())) {
								// 添加自己的消息
								Map<String, Object> hm3 = new HashMap<>();
								hm3.put("title", "您报名的需求已被预约");
								hm3.put("type", "1");
								hm3.put("recevicer_id", lists.get(i).get("id"));
								hm3.put("content", "您报名的需求已被预约");
								messageDao.insertMessage(hm3);
								AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "您报名的需求已被预约");
							} else {
								// 添加自己的消息
								Map<String, Object> hm4 = new HashMap<>();
								hm4.put("title", "报名结束");
								hm4.put("type", "1");
								hm4.put("recevicer_id", lists.get(i).get("id"));
								hm4.put("content", "报名结束");
								messageDao.insertMessage(hm4);
								AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "报名结束");
							}
						}
					} else {
						// 修改该服务单号为已完成
						int flag1 = serverDao.updateServerStatus(Integer.parseInt(order.getServer_id()));
						serverDao.updateOrder(order.getServer_id(), "1");
						AuroraPush.pushTargetForDriver(order.getServer_user_id(), "您的服务已被预约，请注意查看");
					}
					// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

				} else {
					logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				// ------------------------------
				// 处理业务完毕
				// ------------------------------
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
				logger.info("通知签名验证失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 支付服务支付宝回调
	 */
	@Override
	public String aliNotify4(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("====================================begin AlipayService notify");
		String returnStr = "";
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				logger.info("====================================================param s:" + s);
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("====================================================param InputStream:" + sb.toString());
			// 接收支付宝返回的请求参数
			Map<String, String> params = AlipayUtil.createLinkMap(sb.toString());

			logger.info("====================================================param params:" + params);
			String trade_status = params.get("trade_status");
			String out_trade_no = params.get("out_trade_no");
			// String notify_id =
			// json.get("notify_id").toString().substring(2,json.get("notify_id").toString().length()-2);

			logger.info("商户的订单编号：" + out_trade_no);
			logger.info("支付的状态：" + trade_status);

			if (trade_status != null && trade_status.equals("TRADE_SUCCESS")) {

				/**
				 * 支付成功之后的业务处理
				 */
				String passback_paramss = params.get("passback_params");
				String passback_params = URLDecoder.decode(passback_paramss, "utf-8");
				String[] split = passback_params.split(",");
				String orderid = split[0]; // 订单id
				String userid = split[1]; // 用户id
				Integer payMoney = (int) Double.parseDouble(split[2]); // 支付金额
				Integer discountid = Integer.parseInt(split[3]); // 优惠券id
				String order_type = split[4]; // 订单类型
				/**
				 * 增加用户取消订单记录
				 */
				// 查看订单详情
				Order order = payOrderDao.selectOrderInfo(orderid, order_type);
				Map<String, Object> map1 = serverDao.selectUserMoney(userid);
				Double user_money = Double.valueOf(map1.get("money").toString());
				Map<String, Object> platform_map2 = serverDao.selectUserMoney("1");
				Double platform_money = Double.valueOf(platform_map2.get("money").toString());
				serverDao.insertCancelOrder(userid, split[2], "预约预付", order.getOrder_id(), user_money + "",
						Constant.EXPEND, platform_money + Double.valueOf(split[2]) + "", null);
				// serverDao.insertCancelOrder("1", split[2], "平台订单收入",
				// order.getOrder_id(), platform_money +
				// Double.valueOf(split[2]) + "", Constant.INCOME);
				serverDao.returnUserMoney("1", platform_money + Double.valueOf(split[2]) + "");
				if (discountid != 0) {
					// 修改优惠券为已使用
					payOrderDao.updateDiscountStatus(discountid);
				}
				// 修改订单状态为已支付
				int flag = payOrderDao.updateOrderStatus(orderid);
				payOrderDao.updatePayType(orderid, "支付宝");
				// 查看积分使用方式
				Map<String, Object> hashMap = userDao.selectIntegeralWay();
				Integer common_vip = Integer.parseInt(hashMap.get("common_vip").toString()); // 普通会员支付一元获得的积分
				Integer copper_vip = Integer.parseInt(hashMap.get("copper_vip").toString()); // 铜牌会员支付一元获得的积分
				Integer silver_vip = Integer.parseInt(hashMap.get("silver_vip").toString()); // 银牌会员支付一元获得的积分
				Integer gold_vip = Integer.parseInt(hashMap.get("gold_vip").toString()); // 金牌会员支付一元获得的积分
				// 用户支付1元，推荐用户获得的积分
				Integer recommend_integral = Integer.parseInt(hashMap.get("recommend_integral").toString());
				// 查看我的积分
				Map<String, Object> map3 = userDao.selectMyIntegral(userid);
				Integer integral3 = Integer.parseInt(map3.get("integral").toString());

				if (order != null) {
					if (!StringTools.isEmpty(order.getIntegral())) {
						if (Double.valueOf(order.getIntegral()) > 0) {
							// 扣除积分
							payOrderDao.updateUserIntegral(userid,
									integral3 - Double.valueOf(order.getIntegral()) + "");
							// 添加该用户的积分记录
							serverDao.insertIntegralRecord(userid, order.getIntegral(), "积分抵现", null);
						}
					}
				}

				// 查看我的积分
				Map<String, Object> map = userDao.selectMyIntegral(userid);
				Double endintegral = 0.0;// 用户最终的积分
				Double getintegral = 0.0;
				Integer integral = Integer.parseInt(map.get("integral").toString());
				if (integral > 100000) {
					System.out.println("金牌会员");
					getintegral =  Double.valueOf(payMoney) * gold_vip;
					endintegral =  Double.valueOf(payMoney) * gold_vip + integral;
				} else if (integral > 10000) {
					System.out.println("银牌会员");
					getintegral =  Double.valueOf(payMoney) * gold_vip;
					endintegral =  Double.valueOf(payMoney) * silver_vip + integral;
				} else if (integral > 1000) {
					System.out.println("铜牌会员");
					getintegral =  Double.valueOf(payMoney) * gold_vip;
					endintegral =  Double.valueOf(payMoney) * copper_vip + integral;
				} else {
					System.out.println("普通会员");
					getintegral =  Double.valueOf(payMoney) * gold_vip;
					endintegral =  Double.valueOf(payMoney) * common_vip + integral;
				}

				// 修改用户积分
				int flag2 = payOrderDao.updateUserIntegral(userid, endintegral.toString());

				// 添加该用户的积分记录
				int f = serverDao.insertIntegralRecord(userid, getintegral.toString(), "支付奖励", null);
				// 接着查看用户的推荐用户信息
//				List<Map<String, Object>> recommendid = payOrderDao.selectRecommendUserInfo(userid);
//				if (recommendid.size() > 0 && recommendid != null) {
//					for (Map<String, Object> mapre : recommendid) {
//						Integer recommend = Integer.valueOf((int) (Double.valueOf(payMoney) * recommend_integral)); // 推荐用户的奖励积分						
//						// 查看推荐用户的积分
//						Map<String, Object> map2 = userDao.selectMyIntegral(mapre.get("id").toString());
//						Integer integral2 = Integer.parseInt(map2.get("integral").toString());
//						Integer endintegral2 = Integer.valueOf((int) (Double.valueOf(payMoney) * recommend_integral))
//								+ integral2;
//						// 修改推荐用户积分
//						int flag3 = payOrderDao.updateUserIntegral(mapre.get("id").toString(), endintegral2.toString());
//						int fg = serverDao.insertIntegralRecord(mapre.get("id").toString(), recommend.toString(),
//								"积分奖励", userid);
//					}
//				}
				// 添加自己的消息
				Map<String, Object> hm = new HashMap<>();
				hm.put("title", "您已预约了一条服务，请注意查看");
				hm.put("type", "1");
				hm.put("recevicer_id", userid);
				hm.put("content", "您已预约了一条服务，请注意查看");
				messageDao.insertMessage(hm);

				// 添加自己的消息
				Map<String, Object> hm2 = new HashMap<>();
				hm2.put("title", "您的服务已被预约，请注意查看");
				hm2.put("type", "1");
				hm2.put("recevicer_id", order.getServer_user_id());
				hm2.put("content", "您的服务已被预约，请注意查看");
				messageDao.insertMessage(hm2);
				if ("2".equals(order_type)) {
					// 修改该需求单号为已完成
					serverDao.demandSure(Integer.parseInt(order.getServer_id()));
					serverDao.updateOrder(order.getServer_id(), "2");
					List<Map<String, Object>> lists = serverDao
							.selectApplyUserInfo(Integer.parseInt(order.getServer_id()));
					for (int i = 0; i < lists.size(); i++) {
						if (lists.get(i).get("id").toString().equals(order.getServer_user_id())) {
							// 添加自己的消息
							Map<String, Object> hm3 = new HashMap<>();
							hm3.put("title", "您报名的需求已被预约");
							hm3.put("type", "1");
							hm3.put("recevicer_id", lists.get(i).get("id"));
							hm3.put("content", "您报名的需求已被预约");
							messageDao.insertMessage(hm3);
							AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "您报名的需求已被预约");
						} else {
							// 添加自己的消息
							Map<String, Object> hm4 = new HashMap<>();
							hm4.put("title", "报名结束");
							hm4.put("type", "1");
							hm4.put("recevicer_id", lists.get(i).get("id"));
							hm4.put("content", "报名结束");
							messageDao.insertMessage(hm4);
							AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "报名结束");
						}
					}
				} else {
					// 修改该服务单号为已完成
					int flag1 = serverDao.updateServerStatus(Integer.parseInt(order.getServer_id()));
					serverDao.updateOrder(order.getServer_id(), "1");
					AuroraPush.pushTargetForDriver(order.getServer_user_id(), "您的服务已被预约，请注意查看");
				}
				returnStr = "success";
			} else {
				/**
				 * 支付失败后的业务处理
				 */
				returnStr = "failure";
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "failure";
		}
		logger.info("====================================end AlipayService notify" + returnStr);
		return returnStr;
	}

	@Override
	public String aliNotify5(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("====================================begin AlipayService notify");
		String returnStr = "";
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				logger.info("====================================================param s:" + s);
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("====================================================param InputStream:" + sb.toString());
			// 接收支付宝返回的请求参数
			Map<String, String> params = AlipayUtil.createLinkMap(sb.toString());

			logger.info("====================================================param params:" + params);
			String trade_status = params.get("trade_status");
			String out_trade_no = params.get("out_trade_no");
			// String notify_id =
			// json.get("notify_id").toString().substring(2,json.get("notify_id").toString().length()-2);

			logger.info("商户的订单编号：" + out_trade_no);
			logger.info("支付的状态：" + trade_status);

			if (trade_status != null && trade_status.equals("TRADE_SUCCESS")) {
				/**
				 * 支付成功之后的业务处理
				 */
				if (out_trade_no == null) {
					 returnStr = "failure";
				}
				Map<String, Object> map = serverDao.selectComment_(out_trade_no);
				if (map != null) {
					String star_level = map.get("star_level").toString();
					String user_id = map.get("user_id").toString();
					String service_id = map.get("service_id").toString();
					serverService.getReturnData(star_level, user_id, service_id, map);
					 returnStr = "success";
				} else {
					 returnStr = "failure";
				}
			} else {
				/**
				 * 支付失败后的业务处理
				 */
				returnStr = "failure";
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "failure";
		}
		logger.info("====================================end AlipayService notify" + returnStr);
		return returnStr;
	}

	/**
	 * 支付服务微信回调
	 */
	@Override
	public void wxNotify5(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("-------------------------------------------begin notify");
		try {
			// 读取参数
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();
			logger.info("-------------------------------------------begin notify s:" + sb.toString());
			// 解析xml成map
			Map<String, String> m = new HashMap<String, String>();
			m = XMLUtil.doXMLParse(sb.toString());
			logger.info("-------------------------------------------begin notify param:" + m);
			// 过滤空 设置 TreeMap
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			Iterator it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 账号信息
			String key = WeixinCons.WX_APP_KEY; // key

			logger.info(packageParams.toString());
			// 判断签名是否正确
			if (WeixinPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
				// ------------------------------
				// 处理业务开始
				// ------------------------------
				String resXml = "";
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
					// 这里是支付成功
					////////// 执行自己的业务逻辑////////////////
					String out_trade_no = (String) packageParams.get("out_trade_no");

					if (out_trade_no != null) {
						Map<String, Object> map = serverDao.selectComment_(out_trade_no);
						if (map != null) {
							String star_level = map.get("star_level").toString();
							String user_id = map.get("user_id").toString();
							String service_id = map.get("service_id").toString();
							String comment_id = map.get("comment_id").toString();
							// 新增打赏记录
							serverService.getReturnData(star_level, user_id, service_id, map);
							// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
							resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
									+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

						}
					}
					logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				} else {
					logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String intnum = "5.00";
		Integer parseInt =Integer.valueOf((int) (Double.valueOf(intnum)*100));
	       System.out.println(parseInt);
	}
	
}